package com.cf.web.controller;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.cf.expire.ExpireService;
import com.cf.util.SpringBeanUtil;
import com.wf.captcha.Captcha;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * boot-awm-CaptchaController
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/2 上午 10:30
 */
public interface CaptchaController {

    default String out(HttpServletResponse rp) throws IOException {
        this.setHeader(rp);
        Captcha captcha = new GifCaptcha(getWidth(), getHeight(), getLength());
        captcha.out(rp.getOutputStream());
        return captcha.text();
    }

    /**
     * 获取图片的长度
     *
     * @return
     */
    int getLength();

    /**
     * 获取图片的高度
     *
     * @return
     */
    int getHeight();

    /**
     * 获取图片的宽度
     *
     * @return
     */
    int getWidth();

    default void setHeader(HttpServletResponse rp) {
        rp.setContentType("image/gif");
        rp.setHeader("Pragma", "No-cache");
        rp.setHeader("Cache-Control", "no-cache");
        rp.setDateHeader("Expires", 0L);
    }


    default boolean checkCode(String key, String code) {
        String expire = SpringBeanUtil.getBean(ExpireService.class).getExpire(imgKeyPrefix() + key);
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(expire)) {
            return false;
        }
        return expire.toLowerCase().equals(code.toLowerCase());
    }

    default boolean remove(String key) {
        SpringBeanUtil.getBean(ExpireService.class).del(imgKeyPrefix() + key);
        return true;
    }

    String imgKeyPrefix();

    @ApiOperation(value = "获取图形验证码")
    @RequestMapping(value = "/image/captcha", method = {RequestMethod.GET})
    default void captcha(@RequestParam("key") String key, HttpServletRequest request, HttpServletResponse response) throws BizException {
        try {
            if (StringUtils.isEmpty(key)) {
                throw new BizException(EnumReturnCode.ERROR.getCode(), "key缺失！");
            }
            String data = this.out(response);
            SpringBeanUtil.getBean(ExpireService.class).setExpire(imgKeyPrefix() + key, data, 120);
        } catch (IOException e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "验证码服务生成失败！");
        }
    }


}
